import _ from 'lodash';
import {Toast} from 'antd-mobile';


export default class WisonFetch {
    static joinKevValue(obj) {
        let list = [];
        for (let key in obj) {
            let value = obj[key];
            if (_.isArray(value))
                value.map(i => {
                    list.push(`${key}=${i}`);
                    return i;
                });
            else
                list.push(`${key}=${obj[key]}`);
        }
        return list.length ? '?' + list.join('&') : '';
    }

    static get(url, params) {
        return fetch(`${url}${WisonFetch.joinKevValue(params)}`, {credentials: 'include'}).then(r => r.json()).then(r => {
            if (!r.success) {
                Toast.fail(r.error);
            }
            return r;
        });
    }

    static post(url, params, headers) {
        return fetch(url, {
            method: 'POST',
            credentials: 'include',
            headers: headers || {'Accept': 'application/json', 'Content-Type': 'application/json'},
            body: JSON.stringify(params)
        }).then(r => r.json()).then(r => {
            if (!r.success) {
                Toast.fail(r.error);
            }
            return r;
        })
    }

    static put(url, params, headers) {
        return fetch(url, {
            method: 'PUT',
            credentials: 'include',
            body: JSON.stringify(params),
            headers: headers || {'Accept': 'application/json', 'Content-Type': 'application/json'},
        }).then(r => r.json()).then(r => {
            if (!r.success) {
                Toast.fail(r.error);
            }
            return r;
        })
    }

    static delete(url, params, headers) {
        return fetch(url, {
            method: 'DELETE',
            credentials: 'include',
            body: JSON.stringify(params),
            headers: headers || {'Accept': 'application/json', 'Content-Type': 'application/json'},
        }).then(r => r.json()).then(r => {
            if (!r.success) {
                Toast.fail(r.error);
            }
            return r;
        })
    }
}